
package com.sicau.socialpracticesystem.util.upload;

import com.alibaba.excel.annotation.ExcelProperty;

import lombok.extern.slf4j.Slf4j;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;


@Slf4j
public class ValidateHelper {

    private ValidateHelper() {
    }

    private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

    /**
     * 验证参数是否合法
     *
     * @param obj 被验证的对象
     * @param <T> 对象泛型
     * @return 返回null则验证通过，反之不通过 ；ExcelCheckErrDto除row字段外的所有的值 均被设定好
     */
    public static <T> List<ExcelCheckErrDto<T>> validateEntity(T obj, Integer temRow) throws NoSuchFieldException {
        List<ExcelCheckErrDto<T>> list = new ArrayList<>();
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && !set.isEmpty()) {
            for (ConstraintViolation<T> cv : set) {
                Field declaredField = obj.getClass().getDeclaredField(cv.getPropertyPath().toString());
                ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);

                //设置错误消息
                ExcelCheckErrDto<T> errDto = new ExcelCheckErrDto<>();
                errDto.setT(obj);
                errDto.setErrMsg(annotation.value()[0] + cv.getMessage());
                errDto.setCol(annotation.value()[0]);
                errDto.setRow(temRow);
                list.add(errDto);
            }
        }
        return list;
    }

    /**
     * 验证参数是否合法
     *
     * @param obj 被验证的对象
     * @param <T> 对象泛型
     * @return 返回null则验证通过，反之不通过 ；ExcelCheckErrDto除row字段外的所有的值 均被设定好
     */
    private static <T> ExcelCheckErrDto<T> validateParam(T obj) throws NoSuchFieldException {
        ExcelCheckErrDto<T> errDto = null;
        Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
        if (set != null && !set.isEmpty()) {
            errDto = new ExcelCheckErrDto<>();
            errDto.setT(obj);
            for (ConstraintViolation<T> cv : set) {
                Field declaredField = obj.getClass().getDeclaredField(cv.getPropertyPath().toString());
                ExcelProperty annotation = declaredField.getAnnotation(ExcelProperty.class);
                //设置错误消息
                errDto.setErrMsg(annotation.value()[0] + cv.getMessage());
            }
        }
        return errDto;
    }


}